<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2018-05-22
 * Time: 10:40
 */

namespace app\api\controller\v1;


use app\api\controller\BaseController;
use app\api\model\Order as OrderModel;
use app\api\model\Refund as RefundModel;
use app\api\service\Token as TokenService;
use app\api\validate\CheckRefund;
use app\api\validate\IDMustBePositiveInt;
use app\lib\exception\RefundException;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UploadFileException;
use think\Db;
use think\Exception;

class Refund extends BaseController
{
    //上传退款原因图片
    public function uploadImage(){
        if(array_key_exists('refund_pics',$_FILES)){
            $pics_ary = $_FILES;
            $img_url = RefundModel::saveImages($pics_ary);
//            $img_url_ary = array();
//            foreach ($img_url as $k => $v){
//                $v_ary = explode('/',$v);
//                $img_url_ary[$k] = $v_ary[count($v_ary)-1];
//            }
        }else{
            throw new UploadFileException([
                'msg' => '头像未上传或上传过程出现异常，请重新上传'
            ]);
        }
//        return $img_url_ary;
        return $img_url;
    }
    // 申请退款
    public function createRefund(){
        $validate = new CheckRefund();
        $validate->goCheck();
        $uid = TokenService::getCurrentUid();
        $refundInfo = $validate->getDataByRule(input('post.'));
        Db::startTrans();
        try{
            $result = RefundModel::getRefundByOID($refundInfo['refund_oid'], $uid);
//            if(!empty($result)){
//                return json(new SuccessMessage([
//                    'code' => 400,
//                    'msg' => '此订单用户已申请退款，请勿重复操作'
//                ]),201);
//            }
            if(!empty($result)){
                $result = $result->toArray();
                $order_status = $result['order']['status'];
                $refund = RefundModel::get(['oid' => $refundInfo['refund_oid']]);
            }else{
                $order = OrderModel::get(['id' => $refundInfo['refund_oid']]);
                $order_status = $order->status;
                $refund_no = self::makeRefundNo();
                $refund = new RefundModel();
                $refund->refund_no = $refund_no;
            }
            $oid = $refundInfo['refund_oid'];
            $refund->uid = $uid;
            $refund->oid = $oid;
            $refund->reason = $refundInfo['refund_reason'];
            $refund->type = $refundInfo['refund_type'];
            $refund->money = $refundInfo['refund_money'];
            $refund->logistics_company = $refundInfo['refund_logistics_name'];
            $refund->logistics_number = $refundInfo['refund_logistics_no'];

            // $img_len = count($refundInfo['refund_imgs']);
            $refundImgs = $refundInfo['refund_imgs'];
            // if($img_len == 1){
            //     $refund->pic_url_one = $refundImgs[0];
            // }elseif ($img_len == 2){
            //     $refund->pic_url_one = $refundImgs[0];
            //     $refund->pic_url_two = $refundImgs[1];
            // }elseif ($img_len == 3){
            //     $refund->pic_url_one = $refundImgs[0];
            //     $refund->pic_url_two = $refundImgs[1];
            //     $refund->pic_url_three = $refundImgs[2];
            // }else{
            //     $refund->pic_url_one = null;
            //     $refund->pic_url_two = null;
            //     $refund->pic_url_three = null;
            // }
            if(!empty($refundImgs[0])){
                $refund->pic_url_one = $refundImgs[0];
            }else{
                $refund->pic_url_one = null;
            }
            if(!empty($refundImgs[1])){
                $refund->pic_url_two = $refundImgs[1];
            }else{
                $refund->pic_url_two = null;
            }
            if(!empty($refundImgs[2])){
                $refund->pic_url_three = $refundImgs[2];
            }else{
                $refund->pic_url_three = null;
            }
            $refund->save();

            $refund_id = $refund->id;
            if($refund_id && $order_status == 2){
                OrderModel::where('id', '=', $oid)->update(['status' => -2]);
            }
            Db::commit();
            return json(new SuccessMessage([
                'code' => 200,
                'msg' => '申请退款提交成功，请等待审核'
            ]),200);
        }catch (Exception $exception){
            Db::rollback();
            throw $exception;
        }
    }
    // 生成退款单号
    public static function makeRefundNo()
    {
        $yCode = array('K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T');
        $refundSn =
            'R' . $yCode[intval(date('Y')) - 2017] . strtoupper(dechex(date('m'))) . date(
                'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
                '%02d', rand(0, 99));
        return $refundSn;
    }

    // 退款中（-2）获取申请退款的信息
    public function getRefundInfo(){
        $validate = new IDMustBePositiveInt();
        $validate->goCheck();
        $uid = TokenService::getCurrentUid();
        $params = $validate->getDataByRule(input('param.'));
        $oid = $params['id'];
        $refundInfo = RefundModel::getRefundByOID($oid, $uid)->toArray();
        if(empty($refundInfo)){
            throw new RefundException([
                'msg' => '申请退款信息不存在，请确认是否已申请退款或稍后重试'
            ]);
        }
        return $refundInfo;
    }

    // 管理后台点击退款按钮，执行退款操作
    public function doRefund($id){
        if(empty($id)){
            $id = $_GET['id'];
        }
        (new IDMustBePositiveInt())->goCheck();
        $refund = new RefundService($id);
        return $refund->refund();
    }

}